package com.clb.studyproject.ui

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.util.Log
import android.util.LongSparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.forEach
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.clb.studyproject.R

class ChoosePicActivity :AppCompatActivity(R.layout.activity_choose_pic){

    private lateinit var imgList: RecyclerView
    private val PERMISSION_READ_STORAGE = 0x1001
    private val TAG = javaClass.name
    //文件夹列表
    val folderList = LongSparseArray<ImgGroupEntity>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        imgList = findViewById<RecyclerView>(R.id.img_list)
        checkPermission()
    }

    /**
     * 检查存储权限
     */
    private fun checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSION_READ_STORAGE)
        } else {
            loadLocalImg()
        }
    }

    /**
     * 加载本地图片
     */
    private fun loadLocalImg() {
        Thread {
            val imgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val cursor = contentResolver.query(imgUri, null, null, null, null)
            if (cursor == null) {
                Log.d(TAG, "loadLocalImg: 游标为空")
                return@Thread
            }

            while (cursor.moveToNext()) {
                //获取图片的绝对路径
                val path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
                val bucketName = cursor.getString(cursor.getColumnIndexOrThrow("bucket_display_name"))
                val bucketId = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID))

                val folder = folderList.get(bucketId)
                if (folder == null) {
                    val pathList = ArrayList<String>()
                    val imgGroupEntity = ImgGroupEntity()
                    imgGroupEntity.groupName = bucketName
                    pathList.add(path)
                    imgGroupEntity.imgList = pathList
                    folderList.put(bucketId, imgGroupEntity)
                    pathList.clear()
                } else {
                    val imgList = folder.imgList
                    imgList.add(path)
                }
            }
            handler.sendMessage(handler.obtainMessage())
            cursor.close()
        }.start()
    }

    private val handler = object : Handler() {

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d(TAG, "handleMessage: 图片处理完成$folderList")
            renderedPictureList()
        }

    }

    private fun renderedPictureList() {
        val imgLists = ArrayList<String>()
        folderList.forEach { key, value ->
            imgLists.addAll(value.imgList)
        }
        imgList.layoutManager = GridLayoutManager(this,5)
        imgList.adapter = ImgListAdapter(imgLists)
    }

    class ImgListAdapter(val imgLists: ArrayList<String>) : RecyclerView.Adapter<ImgListAdapter.ImageViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
            val inflate = LayoutInflater.from(parent.context).inflate(R.layout.item_img, parent, false)
            return ImageViewHolder(inflate)
        }

        override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
            Glide.with(holder.itemView.context).load(imgLists[position]).into(holder.imgShow)
        }

        override fun getItemCount(): Int {
            return imgLists.size
        }

        class ImageViewHolder(val inflate: View) :RecyclerView.ViewHolder(inflate){
            val imgShow = inflate.findViewById<ImageView>(R.id.img_show)
        }

    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSION_READ_STORAGE -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //权限申请成功
                    loadLocalImg()
                    Toast.makeText(this, "开始加载图片", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "权限申请失败", Toast.LENGTH_SHORT).show()
                }
            }
            else -> {
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}
